package com.yangye.niodemo.rpc.transport;

import com.yangye.niodemo.rpc.protocol.PackageMsg;
import com.yangye.niodemo.rpc.protocol.RpcBody;
import com.yangye.niodemo.rpc.protocol.RpcHeader;
import com.yangye.niodemo.rpc.util.SerDerUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author yangye
 * @date 2020/12/29
 */
public class ServerDecoder extends ByteToMessageDecoder {

	@Override
	protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> out) throws Exception {
		while (byteBuf.readableBytes() >= 200) {
			byte[] headerBytes = new byte[200];
			byteBuf.getBytes(byteBuf.readerIndex(), headerBytes);
			RpcHeader header = (RpcHeader) SerDerUtil.der(headerBytes);

			if (byteBuf.readableBytes() - 200 >= header.getBodyLen()) {
				byteBuf.readBytes(200);

				byte[] bodyBytes = new byte[header.getBodyLen().intValue()];
				byteBuf.readBytes(bodyBytes);
				RpcBody body = (RpcBody) SerDerUtil.der(bodyBytes);
				PackageMsg packageMsg = new PackageMsg(header, body);
				out.add(packageMsg);
			} else {
				// 否则跳出循环，等待下次ByteBuf里有数据继续读取
				break;
			}
		}
	}
}
